package com.cql.web.controller.common;

import com.cql.common.core.DO.MomentDO;
import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DO.UserRelationDO;
import com.cql.common.core.DTO.*;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.core.base.BaseController;
import com.cql.common.core.base.page.TableDataInfo;
import com.cql.common.core.security.LoginUser;
import com.cql.common.exception.user.UserNotExistException;
import com.cql.common.utils.StringUtils;
import com.cql.framework.config.security.service.TokenService;
import com.cql.service.business.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @author cql
 */
@RestController
@RequestMapping("/common")
public class CommonController extends BaseController {

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysDictDataService sysDictDataService;

    @Autowired
    private MomentService momentService;

    @Autowired
    private UserRelationService userRelationService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取基本角色
     *
     * @return
     */
    @GetMapping("/role")
    public AjaxResult getBaseRole() {
        List<RoleDTO> result = roleService.getBaseRole();
        return AjaxResult.success(result);
    }


    /**
     * 校验用户是否存在
     * 存在返回true，否则返回false
     *
     * @param account
     * @return
     */
    @GetMapping("/check/user")
    public AjaxResult checkUserExist(String account) {
        UserDO user = userService.getUserByAccount(account);
        boolean flag = user == null ? false : true;
        return AjaxResult.success(flag);
    }


    /**
     * 获取所有的地点
     *
     * @return
     */
    @GetMapping("/region")
    public AjaxResult getAllRegion() {

        List<ProvinceDTO> result = regionService.listRegion();

        /**
         * 封装数据方便前端操作
         */
        Map<String, CityFirstCharDto> cityMap = new HashMap<>();
        for (ProvinceDTO provinceDTO : result) {

            for (CityDTO city : provinceDTO.getCities()) {
                String firstChar = city.getFirstChar().toUpperCase(Locale.ROOT);
                if (cityMap.containsKey(firstChar)) {
                    cityMap.get(firstChar).getCities().add(city);
                } else {
                    List<CityDTO> cities = new ArrayList<>(80);
                    cities.add(city);
                    CityFirstCharDto cityFirstCharDto = new CityFirstCharDto();
                    cityFirstCharDto.setCities(cities);
                    cityFirstCharDto.setFirstChar(firstChar);
                    cityMap.put(firstChar, cityFirstCharDto);
                }

            }
        }


        AjaxResult ajaxResult = AjaxResult.success();

        ajaxResult.put("cityMap", cityMap.values());
        ajaxResult.put("provinces", result);

        return ajaxResult;
    }


    /**
     * 根据城市中文名或拼音查找城市
     *
     * @param text
     * @return
     */
    @GetMapping("/region/like")
    public AjaxResult searchCityByNameOrPinyin(String text) {

        List<CityDTO> result = regionService.listByNameOrPinyin(text);

        return AjaxResult.success(result);
    }

    /**
     * 获取用户信息，该接口无需权限，允许游客访问
     *
     * @param account
     * @return
     */
    @GetMapping("/user/{account}")
    public AjaxResult getUserInfo(@PathVariable String account) {
        /**
         * 1.用户基本信息：user_id,account,username,descri,avatar,等级
         * 2.用户对应的角色
         */
        UserDTO userDTO = userService.getUserInfoByAccount(account);
        return AjaxResult.success(userDTO);
    }

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/img")
    public AjaxResult uploadImg(@RequestBody @RequestParam("file") MultipartFile file) throws IOException {

        return AjaxResult.success();
    }


    /**
     * 获取标签
     *
     * @return
     */
    @GetMapping("/tags")
    public AjaxResult listTag() {
        List<TagDTO> tagList = tagService.listTag();
        return AjaxResult.success(tagList);
    }

    /**
     * 获取字典数据
     *
     * @param dictType
     * @return
     */
    @GetMapping("/dict/data")
    public AjaxResult getDictData(String dictType) {
        if (StringUtils.isEmpty(dictType)) {
            return AjaxResult.error();
        }
        List<DictDataDTO> data = sysDictDataService.listDictDataByType(dictType);
        return AjaxResult.success(data);
    }


    /**
     * 获取用户的探店列表
     * (1)数据权限
     * (2)分页
     *
     * @param account
     * @param request
     * @return
     */
    @GetMapping("/moment/list")
    public TableDataInfo listMoment(@RequestParam(required = true) String account, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        UserDO user = userService.getUserByAccount(account);
        if (StringUtils.isNull(user)) {
            throw new UserNotExistException();
        }
        UserRelationDO userRelation = null;
        if (StringUtils.isNull(loginUser)) {
            userRelation = userRelationService.getUserRelation(null, account);
        } else {
            userRelation = userRelationService.getUserRelation(loginUser.getUserDO().getAccount(), account);
        }
        startPage();
        List<MomentInfoDTO> list = momentService.listMoment(userRelation, loginUser, user);
        TableDataInfo dataTable = getDataTable(list);
        return dataTable;
    }


    /**
     * TODO 如何更新访问量
     * 获取文章是一个非常本系统非常频繁的操作，如果在获取文章的信息同时又更新数据库中view字段，
     * 会给数据库带来很多的压力，所以，需要使用redis,当到一定时间，就集体更新
     * 同时还要防止用户刷新浏览器，提示预览量
     *
     * @param momentId
     * @param request
     * @return
     */
    @GetMapping("/moment/{momentId}")
    public AjaxResult getMomentById(@PathVariable("momentId") Long momentId, HttpServletRequest request) {
        MomentInfoDTO info = null;
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNull(loginUser)) {
            logger.info("游客-访问文章: {}", momentId);
            info = momentService.getMomentDetailInfo(null, momentId);
        } else {
            logger.info("{}-访问文章: {}", loginUser.getUserDO().getAccount(), momentId);
            info = momentService.getMomentDetailInfo(loginUser.getUserDO().getUserId(), momentId);
        }
        return AjaxResult.success(info);
    }


    /**
     * 需数据校验
     * 获取探店文章评论
     * 分页
     *
     * @param momentId
     * @param request
     * @return
     */
    @GetMapping("/comment/moment")
    public TableDataInfo listCommentOfMoment(@RequestParam(required = true) Long momentId, HttpServletRequest request) {
        List<CommentDTO> result = null;
        LoginUser loginUser = tokenService.getLoginUser(request);
        MomentDO momentDO = momentService.getMomentById(momentId);
        startPage();
        if (StringUtils.isNull(loginUser)) {
            result = commentService.listCommentOfMoment(null, momentDO);
        } else {
            result = commentService.listCommentOfMoment(loginUser.getUserDO().getUserId(), momentDO);
        }
        return getDataTable(result);
    }


    /**
     * 数据权限问题，需要校验
     *
     * @param menuId
     * @param request
     * @return
     */
    @GetMapping("/menu/{menuId}")
    public AjaxResult getMnuById(@PathVariable("menuId") Long menuId, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);


        return AjaxResult.success();
    }


}
